package com.woniuxy.hospital.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class JwtRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Autowired
    private Audience audience;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken)authenticationToken;
        log.debug(token.toString());
        if(token.getPrincipal()==null){
            throw new AuthenticationException("没有JWT");
        }
        String jwt = token.getPrincipal().toString();
        boolean isValid = JwtUtil.parseJwt(jwt,audience.getBase64Secret());//校验
        if(isValid){
            log.debug("doGetAuthenticationInfo---------isValid:"+isValid);
            return new SimpleAuthenticationInfo(jwt,jwt,getName());
        }else{
            throw new AuthenticationException("JWT解析出错");
        }
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
